package com.donger.web.admin.controller.storage;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.donger.auth.utils.SecurityUtil;
import com.donger.business.modules.storage.entity.StorageFile;
import com.donger.business.modules.storage.service.StorageFileService;
import com.donger.business.service.Global;
import com.donger.common.core.annotation.IgnoreAuth;
import com.donger.common.core.utils.Res;
import com.donger.common.core.utils.Result;
import com.donger.common.sequence.sequence.Sequence;
import com.donger.common.storage.minio.service.MinioTemplate;
import com.donger.web.admin.query.storage.FileQuery;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传下载控制器
 */
@RestController
@RequestMapping("/storage")
@Slf4j
public class FileController {

    @Autowired
    private MinioTemplate minioTemplate;

    @Autowired
    private Sequence fileSequence;

    @Autowired
    private StorageFileService storageFileService;


    @SneakyThrows
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        String filename = file.getOriginalFilename();

        String newFileName = fileSequence.nextNo() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());

        String bucketName = Global.getConfig("sys.file.bucketName", "bootfile");
        String website = Global.getConfig("sys.website", "http://localhost:8888");

        minioTemplate.putObject(bucketName, newFileName, file.getInputStream());
        StorageFile storageFile = new StorageFile();
        storageFile.setBucketName(bucketName);
        storageFile.setCreateName(SecurityUtil.getUser().getUsername());
        storageFile.setFileName(newFileName);
        storageFile.setOriginalFileName(filename);
        storageFile.setSize(file.getSize());
        storageFile.setType(file.getContentType());
        storageFile.setUrl(website + "/storage/" + newFileName);
        storageFile.setCreateTime(LocalDateTime.now());
        storageFileService.save(storageFile);
        Map<String, String> map = new HashMap<>();
        map.put("bucketName", bucketName);
        map.put("newFileName", newFileName);
        map.put("filename", filename);
        map.put("url", storageFile.getUrl());
        return Res.ok(map);
    }


    /**
     * 获取文件 直接重定向到对应服务
     *
     * @param fileName 文件空间/名称
     * @param response
     * @return
     */
    @SneakyThrows
    @IgnoreAuth
    @GetMapping("/{fileName:.+}")
    public void file(@PathVariable String fileName, HttpServletResponse response) {
        String bucketName = Global.getConfig("sys.file.bucketName", "bootfile");
        String url = minioTemplate.getObjectURL(bucketName, fileName, 7);
        response.sendRedirect(url);
    }


    @GetMapping("/page")
    public Result page(Page<StorageFile> page, FileQuery fileQuery) {
        storageFileService.page(page, new LambdaQueryWrapper<StorageFile>()
                .like(StrUtil.isNotBlank(fileQuery.getName()), StorageFile::getOriginalFileName, fileQuery.getName())
                .orderByDesc(StorageFile::getCreateTime)
        );
        return Res.ok(page);

    }

}
